package com.banana.sparsearr;

import com.sun.org.apache.xml.internal.security.Init;
import org.junit.jupiter.api.Test;

/**
 * 稀疏数组解决五子棋存储读取
 */
public class SparseArray {
    @Test
    public void testSparse() {
        // 原始二维数组
        int[][] chessArr1 = new int[11][11];
        chessArr1[1][1] = 1;
        chessArr1[10][10] = 2;
        printArr(chessArr1, "原始二维数组：");
        // 转化稀疏数组
        int count = 0;
        for (int[] ints : chessArr1) {
            for (int anInt : ints) {
                if (anInt != 0) {
                    count++;
                }
            }
        }
        int[][] sparseArr = new int[count + 1][3];
        sparseArr[0][0] = chessArr1.length;
        sparseArr[0][1] = chessArr1[1].length;
        sparseArr[0][2] = count;
        int index = 0;
        for (int t = 0; t < chessArr1.length; t++) {
            for (int i = 0; i < chessArr1[t].length; i++) {
                if (chessArr1[t][i] != 0) {
                    index++;
                    sparseArr[index][0] = t;
                    sparseArr[index][1] = i;
                    sparseArr[index][2] = chessArr1[t][i];
                }
            }
        }
        printArr(sparseArr, "稀疏数组：");
        // 读取稀疏数组
        int[][] chessArr2 = new int[sparseArr[0][0]][sparseArr[0][1]];
        for (int i = 1; i < sparseArr.length; i++) {
            chessArr2[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
        }
        printArr(chessArr2, "重新转化的二维数组：");
    }

    private void printArr(int[][] chessArr1, String msg) {
        System.out.println(msg);
        for (int[] ints : chessArr1) {
            for (int anInt : ints) {
                System.out.printf("%d\t", anInt);
            }
            System.out.println();
        }
        System.out.println();
    }
}
